# coding:utf-8
from django.shortcuts import render, HttpResponseRedirect, redirect
import os
from . import config
from .models import User, UserLog

algorithm_instances = {}


def get_algorithm(request):
    instance_id = request.POST.get("instance_id")
    return algorithm_instances[instance_id]


def put_algorithm(algorithm):
    algorithm_instances[algorithm.instance_id] = algorithm


def read_data_source(request, algorithm):
    algorithm.data_source_name = request.POST.get("data_source_name")
    if algorithm.data_source_name == "manual_upload":
        upload_file = request.FILES.get("upload_file")
        upload_file_path = os.path.join(
            config.upload_file_folder_path, upload_file.name)
        with open(upload_file_path, "wb+") as f:
            for chunk in upload_file.chunks():
                f.write(chunk)
        algorithm.readDataSouce(upload_file_path=upload_file_path)
    else:
        algorithm.readDataSouce()


def show_source_code(request):
    context = {}
    context["source_code_url"] = config.jupyter_url_prefix + \
        "/" + request.GET.get("instance_id") + "/source_code.ipynb"
    return HttpResponseRedirect(config.jupyter_url_prefix + "/" + request.GET.get("instance_id") + "/source_code.ipynb")


def login(request):
    # 登录页
    context = {}
    return render(request, "login.html", context)


def login_do(request):
    # 登录验证
    context = {}
    login_name = request.POST.get("login_name")
    password = request.POST.get("password")
    users = User.objects.filter(user_id=login_name, user_password=password)
    if len(users) == 1:
        # 日志记录
        log = UserLog()
        log.user_id = login_name
        log.log_content = "登录"
        log.save()
        # 登录成功
        request.session["login_name"] = login_name
        return redirect("/portal/")
    else:
        # 登录失败
        return render(request, "login_error.html", context)


def portal(request):
    # portal页
    context = {}
    if request.session.has_key("login_name"):
        return render(request, "portal.html", context)
    else:
        return redirect("/login/")


def logout(request):
    # 退出
    if request.session.has_key("login_name"):
        del request.session["login_name"]
    return redirect("/login/")
